<template>
  <div>
      <el-header>
        <el-row class="header-row">
          <el-col :span="12">
            <h1>{{displayName}}</h1>
          </el-col>
        </el-row>
      </el-header>
  <div class="myContainer">
    <!-- 左侧部分：树状图和条形图 -->
    <div class="charts-container">
      <el-card class="justify-text">
        <div>文章数量：{{ works_count }}</div>
        <div>过去两年平均引用次数：{{ summary_stats['2yr_mean_citedness'] }}</div>
        <div>H指数：{{ summary_stats['h_index'] }}</div>
        <div>i10指数：{{ summary_stats['i10_index'] }}</div>
      </el-card>
      <!-- <div ref="treeChart" class="chart"></div> -->
      <!-- <div ref="barChartConcepts" class="chart"></div> -->
      <div class="table-container1">
        相关领域
          <el-table :data="related_concepts" @row-click="handleConceptTableClick">
            <el-table-column prop="display_name" label="领域" />
            <el-table-column prop="level" label="级别" />
            <el-table-column prop="score" label="相似度" />
          </el-table>
      </div>
      <div ref="barChartCounts" class="chart"></div>
    </div>
    <!-- 右侧部分：Element Plus 列表 -->
    <div class="table-container">
      <el-card class="inner-table">
        <template #header>
          相关文献
        </template>
        <div>
          <el-table :data="related_papers" @row-click="handleWXTableClick">
            <el-table-column prop="title" label="标题" width = 700px />
            <el-table-column prop="publication_date" label="出版时间" />
            <el-table-column prop="type" label="种类" />
          </el-table>
        </div>
      </el-card>

      <el-card  class="inner-table">
        <template #header>
          相关学者
        </template>

        <div>
          <el-table :data="related_scholars" @row-click="handleScTableClick">
            <el-table-column prop="display_name" label="姓名" />
            <el-table-column prop="cited_by_count" label="引用次数" />
            <el-table-column prop="works_count" label="文章数量" />
          </el-table>
        </div>
      </el-card>


    </div>
  </div>
</div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue';
import * as echarts from 'echarts';
import { useRouter } from 'vue-router';  
import { req_getConceptInfo,req_getPapersByXConcepts,req_getScholarsByXConcepts } from '../../../api/index.ts';
const router = useRouter();  
const route = router.currentRoute.value;  
const params = route.params;

const treeChart = ref(null);
const barChartConcepts = ref(null);
const barChartCounts = ref(null);
const displayName= ref("未知领域");
const works_count = ref(0)
const conceptId = ref('C71924100')
const summary_stats = ref({})
const counts_by_year = ref([])
const x_concepts = ref([])
const related_concepts = ref([])
const related_papers = ref([])
const related_scholars = ref([])
async function initAllData () {
  conceptId.value = params.concept_id
  await req_getConceptInfo(conceptId.value).then((res)=>{
    displayName.value = res.data.concept.display_name
    works_count.value = res.data.concept.works_count
    summary_stats.value = res.data.concept.summary_stats
    counts_by_year.value = res.data.concept.counts_by_year
    x_concepts.value = res.data.concept.related_concepts
    related_concepts.value = res.data.concept.related_concepts
  })
  await req_getPapersByXConcepts(conceptId.value).then((res)=>{
    console.log(res)
    related_papers.value = res.data.results
  })
  await req_getScholarsByXConcepts(conceptId.value).then((res)=>{
    console.log(res)
    related_scholars.value = res.data.results
  })
  // initTreeChart();
  // initBarChartConcepts();
  initBarChartCounts();
}
const handleWXTableClick = (row) => {
  const toWXid = row.id
  router.push({name: 'paper', params: { 'paper_id' : toWXid }})
}
const handleScTableClick = (row) => {
  const toScId = row.id
  router.push({name: 'scholar', params: { 'scholar_id' : toScId }})
}
const handleConceptTableClick = (row) => {
  const toCCId = row.id
  router.push({name: 'concept', params: { 'concept_id' : toCCId }})
  setTimeout(() => {
    router.replace('/refresh')
  }, 100);

}
const associated_institutions= [
        {
            "id": "https://openalex.org/I4210104572",
            "ror": "https://ror.org/015tnsz82",
            "display_name": "Michigan Sea Grant",
            "country_code": "US",
            "type": "other",
            "relationship": "child"
        },
        {
            "id": "https://openalex.org/I4210163254",
            "ror": "https://ror.org/057mgcy61",
            "display_name": "Michigan Space Grant Consortium",
            "country_code": "US",
            "type": "other",
            "relationship": "child"
        },
        {
            "id": "https://openalex.org/I4210130704",
            "ror": "https://ror.org/035wtm547",
            "display_name": "University of Michigan\u2013Dearborn",
            "country_code": "US",
            "type": "education",
            "relationship": "child"
        },
        {
            "id": "https://openalex.org/I4210092198",
            "ror": "https://ror.org/01c3xc117",
            "display_name": "University of Michigan\u2013Flint",
            "country_code": "US",
            "type": "education",
            "relationship": "child"
        },
        {
            "id": "https://openalex.org/I2799370151",
            "ror": "https://ror.org/05g2hd893",
            "display_name": "Beaumont Health",
            "country_code": "US",
            "type": "nonprofit",
            "relationship": "related"
        },
        {
            "id": "https://openalex.org/I2801799315",
            "ror": "https://ror.org/034npj057",
            "display_name": "Hurley Medical Center",
            "country_code": "US",
            "type": "healthcare",
            "relationship": "related"
        },
        {
            "id": "https://openalex.org/I4210114445",
            "ror": "https://ror.org/01zcpa714",
            "display_name": "Michigan Medicine",
            "country_code": "US",
            "type": "healthcare",
            "relationship": "related"
        }
    ];

  // 初始化一切
  initAllData()

function initTreeChart() {
  const treeData = formatTreeData(associated_institutions);
  const myChart = echarts.init(treeChart.value);
  const option = {
    series: [
      {
        type: 'tree',
        data: [treeData],
        emphasis: {
            focus: 'descendant'
        },
        grid:{
          height: '200%',
          width: '200%',
        },
        right: '40%',
        label: {
            position: 'left',
            verticalAlign: 'middle',
            align: 'right',
            fontSize: 9
          },
          leaves: {
            label: {
              position: 'right',
              verticalAlign: 'middle',
              align: 'left'
            }
          },
        // 其他树状图配置...
      }
    ],
    title:{
      text: "相关机构"
    }
  };
  myChart.setOption(option);
}

function initBarChartConcepts() {
  const myChart = echarts.init(barChartConcepts.value);
  const myConcepts = x_concepts.value.slice(0,10)
  const option = {
    xAxis: {
      type: 'category',
      data: myConcepts.map(item => item.display_name),
      axisLabel: {
        interval : 0,
        rotate : 30
      },
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: myConcepts.map(item => item.score),
      type: 'bar'
    }],
    title:{
      text: "相关领域"
    }
  };
  myChart.setOption(option);
}

function initBarChartCounts() {
  const myChart = echarts.init(barChartCounts.value);
  counts_by_year.value = counts_by_year.value.reverse()
  console.log(counts_by_year.value)
  const option = {
    xAxis: {
      type: 'category',
      data: counts_by_year.value.map(item => item.year),
    },
    grid:{
          left: '14%',
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: counts_by_year.value.map(item => item.works_count),
      type: 'bar'
    }],
    title:{
      text: "年出版量"
    }
  };
  myChart.setOption(option);
}

function formatTreeData(data) {
  let relatedData = []
  let childData = []
  relatedData.push({"display_name": `${displayName.value}`})
  data.map(item => {
    if(item.relationship === 'child'){
      relatedData.push(item)
    }else{
      childData.push(item)
    }
  })
  // 格式化树状图数据
  return {
    children: relatedData.map(item => ({
      name: item.display_name,
      children: item.display_name === `${displayName.value}` ? childData.map(item => ({
        name: item.display_name,
      })) : []
    }))
  };
}
</script>

<style scoped>
.myContainer {
  display: flex;
  height: 90vh; /* 或根据实际需求调整高度 */
  padding-top: 15px;
}
.header-row {
  display: flex;
  align-items: center;
  border-bottom: 3px solid rgb(212, 212, 212);
  height: 70px;
}
.search-col {
  padding-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  text-align: right;
}
.option {
  width: 100px;
}
.attention{
  margin-right: 10px;
}
.input {
  flex: 1;  
}
.charts-container {
  flex: 1; /* 左侧占 1/3 */
  display: flex;
  flex-direction: column;
  height: 120%;
  padding: 10px;
}
.table-container1 {
  flex: 2; /* 右侧占 2/3 */
  display: flex;
  flex-direction: column;
  padding: 10px;
  display: block;
  overflow-y: scroll;
}
.table-container {
  flex: 2; /* 右侧占 2/3 */
  display: flex;
  flex-direction: column;
  padding: 10px;
  height: 130%;
}

.inner-table {
  display: block;
  overflow-y: scroll;
  height: 45%;
  margin-bottom: 10px;
}

.chart {
  margin-top: 20px;
  flex: 2; /* 使得每个图表平均分配空间 */
  margin-bottom: 10px;
}
.justify-text {  
    display: flex;  
    flex-direction: column;  
    align-items: flex-start;  
    justify-content: space-between;;  
    width: 100%;
}
.justify-text div {  
  margin-bottom: 10px;  
}  
</style>